<?php


namespace app\system\service;

class CardAppService
{
	public static function get_card_list($options)
	{
		$where = self::get_card_conditions($options);
		$list = \think\Db::name("app_card_user")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_card_user")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$data[] = self::get_array_info($item);
		}
		return ["code" => \app\system\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	private static function get_card_conditions($options)
	{
		$where[] = ["appid", "=", $options["appid"]];
		if (isset($options["id"]) && $options["id"] != "") {
			$where[] = ["id", "=", $options["id"]];
		}
		if (isset($options["ids"]) && $options["ids"] != "") {
			$where[] = ["id", "in", $options["ids"]];
		}
		if (isset($options["card_list"]) && $options["card_list"] != "") {
			// 使用 BINARY 关键字实现区分大小写的 IN 查询
			$cardList = is_array($options["card_list"]) ? $options["card_list"] : explode(',', $options["card_list"]);
			$cardListEscaped = array_map(function($card) {
				return "'" . addslashes($card) . "'";
			}, $cardList);
			$where[] = ["", "exp", \think\Db::raw("BINARY `card` IN (" . implode(',', $cardListEscaped) . ")")];
		}
		if (isset($options["batch_number"]) && $options["batch_number"] != "") {
			$batch = \think\Db::name("app_card_batch")->where([["number", "like", "%{$options["batch_number"]}%"]])->find();
			if (!empty($batch)) {
				$where[] = ["batch_id", "=", $batch["id"]];
			}
		}
		if (isset($options["batch_remarks"]) && $options["batch_remarks"] != "") {
			$batch = \think\Db::name("app_card_batch")->where([["remarks", "like", "%{$options["batch_remarks"]}%"]])->find();
			if (!empty($batch)) {
				$where[] = ["batch_id", "=", $batch["id"]];
			}
		}
		if (isset($options["batch_id"]) && $options["batch_id"] != "") {
			$where[] = ["batch_id", "=", $options["batch_id"]];
		}
		if (isset($options["time_type"]) && $options["time_type"] != "") {
			$where[] = ["time_type", "=", $options["time_type"]];
		}
		if (isset($options["time_value"]) && $options["time_value"] != "") {
			$where[] = ["time_value", "=", $options["time_value"]];
		}
		if (isset($options["status"]) && $options["status"] != "") {
			$where[] = ["status", "=", $options["status"]];
		}
		if (isset($options["disable"]) && $options["disable"] != "") {
			$where[] = ["disable", "=", $options["disable"]];
		}
		if (isset($options["expire"]) && $options["expire"] != "") {
			if ($options["expire"] == 1) {
				$where[] = ["status", "=", 1];
				$where[] = ["endtime", "<", time()];
			} else {
				$where[] = ["", "exp", \think\Db::raw("status=0 or endtime>" . time())];
			}
		}
		if (isset($options["time_section_type"]) && $options["time_section_type"] != "" && !empty($options["time_section_start"])) {
			$time_section_field = "addtime";
			if ($options["time_section_type"] == 1) {
				$time_section_field = "usetime";
			} elseif ($options["time_section_type"] == 2) {
				$time_section_field = "endtime";
			} elseif ($options["time_section_type"] == 3) {
				$time_section_field = "acttime";
			}
			$where[] = [$time_section_field, ">=", strtotime($options["time_section_start"])];
			if (!empty($options["time_section_end"])) {
				$where[] = [$time_section_field, "<", strtotime($options["time_section_end"])];
			}
		}
		if (isset($options["agent_id"]) && $options["agent_id"] != "") {
			$where[] = ["agent_id", "=", $options["agent_id"]];
		}
		if (isset($options["card"]) && $options["card"] != "") {
			// 使用 BINARY 关键字实现区分大小写的模糊查询
			$where[] = ["", "exp", \think\Db::raw("BINARY `card` LIKE '%" . addslashes($options["card"]) . "%'")];
		}
		if (isset($options["remarks"]) && $options["remarks"] != "") {
			$where[] = ["remarks", "like", "%" . $options["remarks"] . "%"];
		}
		if (isset($options["online"]) && $options["online"] != "") {
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			$minimum_active_time = getUserMinimumActiveTime($app);
			if ($options["online"] == 1) {
				$where[] = ["acttime", ">=", $minimum_active_time];
				$where[] = ["force_offline_status", "=", 0];
			} else {
				$where[] = ["", "exp", \think\Db::raw("force_offline_status=1 or acttime<" . $minimum_active_time)];
			}
		}
		return $where;
	}
	public static function get_array_info($item)
	{
		$app = \think\Db::name("app")->where(["id" => $item["appid"]])->find();
		$item["machine_code"] = getUserMachineCodeList($item["machine_code"]);
		$minimum_active_time = getUserMinimumActiveTime($app);
		$online_machine_list = \think\Db::name("app_card_user_login_machine")->where([["uid", "=", $item["id"]], ["active_time", ">", $minimum_active_time], ["force_offline_status", "=", 0], ["token_status", "=", 0]])->select();
		$item["online_machine_list"] = $online_machine_list;
		$item["is_on_line"] = count($online_machine_list) > 0 && $item["force_offline_status"] == 0;
		$item["private_data"] = get_app_user_private_data($app, $item["private_data"]);
		$item["batch_info"] = \think\Db::name("app_card_batch")->where(["id" => $item["batch_id"]])->find();
		$item["binding_ip_list"] = json_decode($item["binding_ip_list"], true) ?? [];
		return $item;
	}
	public static function get_card_info($options)
	{
		$item = \think\Db::name("app_card_user")->where(["id" => $options["id"], "appid" => $options["appid"]])->find();
		if (empty($item)) {
			return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
		}
		return ["code" => \app\system\model\Code::success, "data" => self::get_array_info($item)];
	}
	public static function add_card($options)
	{
		// 临时提高内存限制，防止导入大量卡密时内存不足
		@ini_set('memory_limit', '512M');
		// 设置最大执行时间为 5 分钟
		@set_time_limit(300);

		\think\Db::startTrans();
		try {
			$app = \think\Db::name("app")->where("id", $options["appid"])->find();
			$list = [];
			if (empty($options["add_mode"])) {
				$num = $options["num"];
			} else {
				if ($options["add_mode"] == 1) {
					$num = count($options["custom_list"]);
				} elseif ($options["add_mode"] == 2) {
					$num = count($options["importCardTableData"]);
				}
			}
			if (\app\common\server\ConfigServer::get("system", \app\common\model\DefaultConfig::SystemTestDemoField, false) && $num > 2) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前站点为演示站点,一次最多只能生成2个" . \app\common\model\DefaultConfig::SystemTestDemoTipsSuffixText];
			}
			$isSystemAuthUnpaid = isSystemAuthUnpaid();
			if ($isSystemAuthUnpaid && \app\common\model\FreeQuota::CardAddCardLimitNum < $num) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,一次最多只能生成" . \app\common\model\FreeQuota::CardAddCardLimitNum . ",您可分多次生成" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			if ($isSystemAuthUnpaid && \think\Db::name("app_card_user")->where(["appid" => $options["appid"]])->count() + $num > \app\common\model\FreeQuota::CardAppUserQuota) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,一个应用卡密最多" . \app\common\model\FreeQuota::CardAppUserQuota . "个卡密" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			$today = \think\helper\Time::today();
			if ($isSystemAuthUnpaid && \think\Db::name("app_card_user")->where([["appid", "=", $options["appid"]], ["addtime", "between", $today]])->count() + $num > \app\common\model\FreeQuota::CardAppDailyAddCard) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,一个应用每天最多只能生成" . \app\common\model\FreeQuota::CardAppDailyAddCard . "个卡密" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			if ($isSystemAuthUnpaid && \think\Db::name("app")->count() > \app\common\model\FreeQuota::AppQuota) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,最多只能拥有" . \app\common\model\FreeQuota::AppQuota . "个应用" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			$batch_number = uniqid();
			$batch_id = \think\Db::name("app_card_batch")->insertGetId(["appid" => $app["id"], "time" => time(), "num" => $num, "number" => $batch_number, "remarks" => $options["batch_remarks"] ?? "", "card_type" => $options["type"] ?? 0, "card_time_type" => $options["time_type"] ?? 0, "card_value" => $options["time_value"] ?? 1]);
			if (empty($options["add_mode"])) {
				$head = empty($options["head"]) ? "" : $options["head"];
				$foot = empty($options["foot"]) ? "" : $options["foot"];
				for ($i = 0; $i < $num; $i++) {
					$body = getAddCardBodyStructure($options["body"] ?? 0, $options["transform"] ?? 0, $options["card_length"] ?? 0);
					$card = $head . $body . $foot;
					$list[] = $card;
					$uid = \think\Db::name("app_card_user")->insertGetId(["appid" => $options["appid"], "card" => $card, "time_type" => $options["time_type"], "time_value" => $options["time_value"], "addtime" => time(), "batch_id" => $batch_id]);
					if (!empty($options["point"])) {
						\app\api\common\card\Finance::set($uid, "point", $options["point"], 0, "后台添加授权赠送", \app\common\model\CardAppModel::UserPointLogSourceAdminControl);
					}
				}
			} else {
				if ($options["add_mode"] == 1) {
					foreach ($options["custom_list"] as $card) {
						if (countCardCaseSensitive("app_card_user", ["appid" => $options["appid"], "card" => $card]) == 0) {
							$list[] = $card;
							$uid = \think\Db::name("app_card_user")->insertGetId(["appid" => $options["appid"], "card" => $card, "time_type" => $options["time_type"], "time_value" => $options["time_value"], "addtime" => time(), "batch_id" => $batch_id]);
							if (!empty($options["point"])) {
								\app\api\common\card\Finance::set($uid, "point", $options["point"], 0, "后台添加授权赠送", \app\common\model\CardAppModel::UserPointLogSourceAdminControl);
							}
						}
					}
				} elseif ($options["add_mode"] == 2) {
					foreach ($options["importCardTableData"] as $data) {
						if (!(isset($data["卡密"]) && isset($data["时长类型"]) && isset($data["时长面值"])) || !in_array($data["时长类型"], \app\common\model\CardTimeType::getAllValue())) {
							continue;
						}
						if (countCardCaseSensitive("app_card_user", ["appid" => $options["appid"], "card" => $data["卡密"]]) == 0) {
							$list[] = $data["卡密"];
							$uid = \think\Db::name("app_card_user")->insertGetId(["appid" => $options["appid"], "card" => $data["卡密"], "time_type" => $data["时长类型"], "time_value" => $data["时长面值"], "endtime" => isset($data["到期时间"]) ? is_numeric($data["到期时间"]) ? $data["到期时间"] : strtotime($data["到期时间"]) : "", "status" => isset($data["到期时间"]) ? 1 : 0, "usetime" => isset($data["到期时间"]) ? time() : 0, "agent_id" => $data["关联代理ID"] ?? "", "machine_code" => $data["绑定机器码"] ?? "", "addtime" => time(), "batch_id" => $batch_id]);
							if (!empty($data["积分点数"])) {
								\app\api\common\card\Finance::set($uid, "point", $data["积分点数"], 0, "后台自定义导入卡密", \app\common\model\CardAppModel::UserPointLogSourceAdminControl);
							}
						}
					}
				}
			}
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "data" => ["list" => $list, "string" => implode("\n", $list), "batch" => ["id" => $batch_id, "number" => $batch_number]], "msg" => "生成完成,成功:" . count($list) . "个,失败:" . ($num - count($list)) . "个"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function edit_card($options)
	{
		\think\Db::startTrans();
		try {
			$user = \think\Db::name("app_card_user")->where(["id" => $options["id"], "appid" => $options["appid"]])->find();
			if (empty($user)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			$data = ["machine_code_binding_top_limit" => $options["machine_code_binding_top_limit"] ?? 0, "online_machine_upper_limit" => $options["online_machine_upper_limit"] ?? 0, "ip_binding_top_limit" => $options["ip_binding_top_limit"] ?? 0, "machine_ip_binding_top_limit" => $options["machine_ip_binding_top_limit"] ?? 0, "machine_code" => empty($options["machine_code"]) ? "" : json_encode($options["machine_code"], JSON_UNESCAPED_UNICODE), "binding_ip_list" => empty($options["binding_ip_list"]) ? "" : json_encode($options["binding_ip_list"], JSON_UNESCAPED_UNICODE), "private_data" => empty($options["private_data"]) ? $user["private_data"] : json_encode($options["private_data"], JSON_FORCE_OBJECT), "remarks" => empty($options["remarks"]) ? $user["remarks"] : $options["remarks"]];
			if (!empty($options["unbinding_machine_code"]) || empty($options["machine_code"]) && $user["machine_code"]) {
				$data["machine_code"] = "";
				$data["force_offline_status"] = 1;
				\think\Db::name("app_card_user_unbinding_log")->insert(["appid" => $options["appid"], "card_id" => $user["id"], "time" => time(), "source" => \app\common\model\CardAppModel::UserUnBindingLogSourceAdminControl]);
			}
			if (isset($options["endtime"]) && $options["endtime"] != $user["endtime"]) {
				\app\api\common\card\Finance::set($user, "endtime", $options["endtime"], 0, "后台操作", \app\common\model\CardAppModel::UserCardEndTimeLogSourceAdminControl);
			}
			if (isset($options["point"]) && $options["point"] != $user["point"]) {
				$point_type = $options["point"] > $user["point"] ? 0 : 1;
				if ($point_type == 0) {
					$point_number = $options["point"] - $user["point"];
				} else {
					$point_number = $user["point"] - $options["point"];
				}
				\app\api\common\card\Finance::set($user, "point", $point_number, $point_type, "后台操作", \app\common\model\CardAppModel::UserPointLogSourceAdminControl);
			}
			if (!empty($options["card"])) {
				$card = findCardCaseSensitive("app_card_user", ["card" => $options["card"], "appid" => $options["appid"]]);
				if (!empty($card) && $card["id"] != $user["id"]) {
					return ["code" => \app\system\model\Code::fail, "msg" => "该卡密卡号已存在"];
				}
				$data["card"] = $options["card"];
			}
			\think\Db::name("app_card_user")->where(["id" => $options["id"]])->update($data);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function del_card($options)
	{
		\think\Db::startTrans();
		try {
			$new = \think\Db::name("app_card_user")->where(["id" => $options["id"]])->find();
			if (empty($new)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_card_user")->where(["id" => $options["id"], "appid" => $options["appid"]])->delete();
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function del_card_batch($options)
	{
		\think\Db::startTrans();
		try {
			$new = \think\Db::name("app_card_batch")->where(["id" => $options["id"]])->find();
			if (empty($new)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_card_batch")->where(["id" => $options["id"], "appid" => $options["appid"]])->delete();
			\think\Db::name("app_card_user")->where(["batch_id" => $options["id"], "appid" => $options["appid"]])->delete();
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function get_card_batch_list($options)
	{
		$where = [];
		$where[] = ["appid", "=", $options["appid"]];
		if (isset($options["id"]) && $options["id"] != "") {
			$where[] = ["id", "=", $options["id"]];
		}
		if (isset($options["agent_id"]) && $options["agent_id"] != "") {
			$where[] = ["agent_id", "=", $options["agent_id"]];
		}
		if (isset($options["number"]) && $options["number"] != "") {
			$where[] = ["number", "like", "%" . $options["number"] . "%"];
		}
		if (isset($options["remarks"]) && $options["remarks"] != "") {
			$where[] = ["remarks", "like", "%" . $options["remarks"] . "%"];
		}
		$list = \think\Db::name("app_card_batch")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_card_batch")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$item["card_info"] = ["total" => \think\Db::name("app_card_user")->where(["batch_id" => $item["id"]])->count(), "used_total" => \think\Db::name("app_card_user")->where(["status" => 1, "batch_id" => $item["id"]])->count(), "not_used_total" => \think\Db::name("app_card_user")->where(["status" => 0, "batch_id" => $item["id"]])->count(), "expired_total" => \think\Db::name("app_card_user")->where([["status", "=", 1], ["endtime", "<", time()], ["batch_id", "=", $item["id"]]])->count()];
			$data[] = $item;
		}
		return ["code" => \app\system\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages, "all_card_data" => ["total" => \think\Db::name("app_card_user")->where(["appid" => $options["appid"]])->count(), "used_total" => \think\Db::name("app_card_user")->where(["appid" => $options["appid"], "status" => 1])->count(), "not_used_total" => \think\Db::name("app_card_user")->where(["status" => 0, "appid" => $options["appid"]])->count(), "expired_total" => \think\Db::name("app_card_user")->where([["status", "=", 1], ["endtime", "<", time()]])->count(), "hour_total" => \think\Db::name("app_card_user")->where(["appid" => $options["appid"], "time_type" => 1])->count(), "day_total" => \think\Db::name("app_card_user")->where(["appid" => $options["appid"], "time_type" => 2])->count(), "week_total" => \think\Db::name("app_card_user")->where(["appid" => $options["appid"], "time_type" => 3])->count(), "month_total" => \think\Db::name("app_card_user")->where(["appid" => $options["appid"], "time_type" => 4])->count(), "year_total" => \think\Db::name("app_card_user")->where(["appid" => $options["appid"], "time_type" => 5])->count(), "perpetual_total" => \think\Db::name("app_card_user")->where(["appid" => $options["appid"], "time_type" => 6])->count()]];
	}
	public static function card_disable($options)
	{
		\think\Db::startTrans();
		try {
			$row = \think\Db::name("app_card_user")->where(["id" => $options["id"]])->find();
			if (empty($row)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_card_user")->where(["id" => $options["id"]])->update(["disable" => !$row["disable"]]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function export_card_user_table($options)
	{
		// 临时提高内存限制，防止导出大量数据时内存不足
		@ini_set('memory_limit', '512M');
		// 设置最大执行时间为 5 分钟
		@set_time_limit(300);

		$result = CardAppService::get_card_list($options);
		if ($result["code"] == \app\system\model\Code::success) {
			$list = $result["data"];
			if (empty($list)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "无数据导出"];
			}
			$data[] = ["ID", "卡密", "类型", "时长", "状态", "机器码", "生成时间", "使用时间", "到期时间", "活跃时间", "批次ID", "代理ID"];
			foreach ($list as $item) {
				// 确保所有字段都是字符串类型，避免 PHPExcel 类型错误
				$machine_code = is_array($item["machine_code"]) ? json_encode($item["machine_code"], JSON_UNESCAPED_UNICODE) : (string)$item["machine_code"];
				$row = [
					(string)$item["id"],
					(string)$item["card"],
					(string)\app\common\model\CardTimeType::getName($item["time_type"]),
					(string)$item["time_value"],
					$item["status"] == 1 ? "已使用" : "未使用",
					$machine_code,
					date("Y-m-d H:i:s", $item["addtime"]),
					$item["usetime"] ? date("Y-m-d H:i:s", $item["usetime"]) : "",
					$item["endtime"] ? date("Y-m-d H:i:s", $item["endtime"]) : "",
					$item["acttime"] ? date("Y-m-d H:i:s", $item["acttime"]) : "",
					(string)($item["batch_id"] ?? ""),
					(string)($item["agent_id"] ?? "")
				];
				$data[] = $row;
			}
			unset($list);
			$res = \app\common\server\Export::export($options["export_file_type"], "单码卡密导出_" . date("Y-m-d H:i:s"), $data, 1);
			return ["code" => \app\system\model\Code::success, "msg" => "文件生成完成", "data" => ExportService::export_return_data_structure($res)];
		} else {
			return $result;
		}
	}
	public static function get_card_account_finance_log($options)
	{
		$where = [];
		$where[] = ["appid", "=", $options["appid"]];
		if (isset($options["uid"]) && $options["uid"] != "") {
			$where[] = ["uid", "=", $options["uid"]];
		}
		if (isset($options["field"]) && $options["field"] != "") {
			$where[] = ["field", "=", $options["field"]];
		}
		if (isset($options["type"]) && $options["type"] != "") {
			$where[] = ["type", "=", $options["type"]];
		}
		if (isset($options["source"]) && $options["source"] != "") {
			$where[] = ["source", "=", $options["source"]];
		}
		if (isset($options["remarks"]) && $options["remarks"] != "") {
			$where[] = ["remarks", "like", "%" . $options["remarks"] . "%"];
		}
		if (!empty($options["time_scope"]) && count($options["time_scope"]) > 1) {
			$time_scope = $options["time_scope"];
			$where[] = ["time", ">=", strtotime($time_scope[0])];
			$where[] = ["time", "<", strtotime($time_scope[1])];
		}
		$list = \think\Db::name("app_card_user_finance_log")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_card_user_finance_log")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$item["card_info"] = \think\Db::name("app_card_user")->where(["id" => $item["uid"]])->field("id,card,time_type,time_value,agent_id,batch_id")->find();
			$data[] = $item;
		}
		return ["code" => \app\system\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	public static function get_card_unbinding_log($options)
	{
		$where = [];
		$where[] = ["appid", "=", $options["appid"]];
		if (isset($options["uid"]) && $options["uid"] != "") {
			$where[] = ["card_id", "=", $options["uid"]];
		}
		if (isset($options["source"]) && $options["source"] != "") {
			$where[] = ["source", "=", $options["source"]];
		}
		$list = \think\Db::name("app_card_user_unbinding_log")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_card_user_unbinding_log")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$item["card_info"] = \think\Db::name("app_card_user")->where(["id" => $item["card_id"]])->field("id,card,time_type,time_value,agent_id,batch_id")->find();
			$data[] = $item;
		}
		return ["code" => \app\system\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	public static function condition_del_card($options)
	{
		\think\Db::startTrans();
		try {
			$where = self::get_card_conditions($options);
			$count = \think\Db::name("app_card_user")->where($where)->count();
			\think\Db::name("app_card_user")->where($where)->delete();
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "成功删除{$count}个卡密"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function condition_unbinding_card($options)
	{
		\think\Db::startTrans();
		try {
			$where = self::get_card_conditions($options);
			$count = \think\Db::name("app_card_user")->where($where)->count();
			\think\Db::name("app_card_user")->where($where)->update(["machine_code" => ""]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "成功解绑{$count}个卡密"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function condition_increase_duration_card($options)
	{
		\think\Db::startTrans();
		try {
			$where = self::get_card_conditions($options);
			$list = \think\Db::name("app_card_user")->where($where)->select();
			$s = 0;
			$time = time();
			foreach ($list as $item) {
				$suffix_tips = "";
				if ($item["status"] == 1) {
					$s++;
					if ($time < $item["endtime"]) {
						$number = $item["endtime"] + $options["value"];
					} else {
						$number = $time + $options["value"];
						$suffix_tips = "(因卡密过期则变更为" . ($number - $item["endtime"]) . "秒)";
					}
					\app\api\common\card\Finance::set($item, "endtime", $number, 0, "条件筛选增加时长{$options["value"]}秒" . $suffix_tips, \app\common\model\CardAppModel::UserCardEndTimeLogSourceCardConditionIncreaseDuration);
				}
			}
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "成功增加时长" . $s . "个卡密"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function condition_increase_point_card($options)
	{
		\think\Db::startTrans();
		try {
			$where = self::get_card_conditions($options);
			$list = \think\Db::name("app_card_user")->where($where)->select();
			if ($options["value"] < 0) {
				$number = 0 - $options["value"];
				$type = 1;
			} else {
				$number = $options["value"];
				$type = 0;
			}
			foreach ($list as $item) {
				\app\api\common\card\Finance::set($item, "point", $number, $type, "条件筛选增加积分{$number}个", \app\common\model\CardAppModel::UserPointLogSourceCardConditionIncrease);
			}
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "成功操作积分" . count($list) . "个卡密"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function condition_force_offline_card($options)
	{
		\think\Db::startTrans();
		try {
			$where = self::get_card_conditions($options);
			$count = \think\Db::name("app_card_user")->where($where)->count();
			\think\Db::name("app_card_user")->where($where)->update(["force_offline_status" => 1]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "成功下线{$count}个在线卡密"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function condition_disable_card($options)
	{
		\think\Db::startTrans();
		try {
			$where = self::get_card_conditions($options);
			$count = \think\Db::name("app_card_user")->where($where)->count();
			\think\Db::name("app_card_user")->where($where)->update(["disable" => $options["value"]]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "msg" => "成功设置{$count}个卡密禁启用状态"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function card_force_offline($options)
	{
		\think\Db::startTrans();
		try {
			$row = \think\Db::name("app_card_user")->where(["id" => $options["id"]])->find();
			if (empty($row)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_card_user")->where(["id" => $options["id"]])->update(["force_offline_status" => 1]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function card_force_offline_machine($options)
	{
		\think\Db::startTrans();
		try {
			$login_machine = \think\Db::name("app_card_user_login_machine")->where(["id" => $options["id"]])->find();
			if (empty($login_machine)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			$row = \think\Db::name("app_card_user")->where(["id" => $login_machine["uid"]])->find();
			if (empty($row)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "卡密不存在"];
			}
			\think\Db::name("app_card_user_login_machine")->where(["id" => $login_machine["id"]])->update(["force_offline_status" => 1]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function revise_batch_remarks($options)
	{
		\think\Db::startTrans();
		try {
			$new = \think\Db::name("app_card_batch")->where(["id" => $options["id"]])->find();
			if (empty($new)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_card_batch")->where(["id" => $options["id"], "appid" => $options["appid"]])->update(["remarks" => $options["value"]]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function get_login_machine_list($options)
	{
		$item = \think\Db::name("app_card_user")->where(["id" => $options["id"], "appid" => $options["appid"]])->find();
		if (empty($item)) {
			return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
		}
		$where[] = ["uid", "=", $options["id"]];
		$where[] = ["appid", "=", $options["appid"]];
		if (isset($options["machine_code"]) && $options["machine_code"] != "") {
			$where[] = ["machine_code", "like", "%" . $options["machine_code"] . "%"];
		}
		if (isset($options["ip"]) && $options["ip"] != "") {
			$where[] = ["ip", "like", "%" . $options["ip"] . "%"];
		}
		$list = \think\Db::name("app_card_user_login_machine")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_card_user_login_machine")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		$app = \think\Db::name("app")->where(["id" => $item["appid"]])->find();
		$minimum_active_time = getUserMinimumActiveTime($app);
		foreach ($list as $item) {
			$item["is_on_line"] = $minimum_active_time < $item["active_time"];
			$item["binding_ip_list"] = json_decode($item["binding_ip_list"], true) ?? [];
			$data[] = $item;
		}
		return ["code" => \app\system\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	public static function del_login_machine($options)
	{
		\think\Db::startTrans();
		try {
			$new = \think\Db::name("app_card_user_login_machine")->where(["id" => $options["id"]])->find();
			if (empty($new)) {
				return ["code" => \app\system\model\Code::fail, "msg" => "id不存在"];
			}
			\think\Db::name("app_card_user_login_machine")->where(["id" => $options["id"], "appid" => $options["appid"]])->delete();
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
}